package com.yzc.android.network.mock;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by yzc on 16/5/5.
 */
public class KDFakeResponseInterceptor implements Interceptor {

    private IFakeResponse mFakeResponse;
    private boolean triggerOnce = true;

    @Override
    public Response intercept(final Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        if (mFakeResponse == null) {
            return originalResponse;
        }

        Response fakedResponse = originalResponse.newBuilder() //
                .code(mFakeResponse.httpCode()) //
                .body(ResponseBody.create(MediaType.parse(mFakeResponse.mediaType()), mFakeResponse.body())) //
                .build();

        if (triggerOnce) {
            mFakeResponse = null;
        }

        originalResponse.body().close();
        return fakedResponse;
    }

    public IFakeResponse getFakeResponse() {
        return mFakeResponse;
    }

    public void setFakeResponse(final IFakeResponse fakeResponse) {
        mFakeResponse = fakeResponse;
    }

    public void clearFakeResponse() {
        mFakeResponse = null;
    }

    public void setTriggerOnce(boolean triggerOnce) {
        this.triggerOnce = triggerOnce;
    }

    public boolean isTriggerOnce() {
        return triggerOnce;
    }
}
